package crons

import (
	"context"
	"github.com/gogf/gf/v2/os/gtime"
	"hotgo/internal/consts"
	"hotgo/internal/dao"
	"hotgo/internal/library/cron"
	"hotgo/internal/library/payment"
	"hotgo/internal/model/entity"
	"hotgo/internal/model/input/payin"
	"hotgo/internal/service"
	"time"
)

// 主动查询支付订单
func init() {
	cron.Register(PayOrderCheck)
}

var PayOrderCheck = &cPayOrderCheck{name: "pay_order_check"}

type cPayOrderCheck struct {
	name string
}

func (c *cPayOrderCheck) GetName() string {
	return c.name
}

func (c *cPayOrderCheck) Execute(ctx context.Context, parser *cron.Parser) (err error) {
	var (
		orderList []entity.Order
	)
	if err = service.SysUserOrder().Model(ctx).Where(dao.Order.Columns().Status, consts.UserOrderStatusNot).
		WhereLTE(dao.Order.Columns().CreatedAt, gtime.Now().Add(-1*time.Minute)).
		Scan(&orderList); err != nil {
		parser.Logger.Warning(ctx, "cron PayOrderCheck Execute err:%+v", err)
	}
	for _, order := range orderList {
		var payLog entity.PayLog
		// 查询支付记录
		if err = service.Pay().Model(ctx).Where(dao.PayLog.Columns().OrderSn, order.Uid).Scan(&payLog); err != nil {
			parser.Logger.Warning(ctx, "cron PayOrderCheck Execute err:%+v", err)
		}
		if payLog.PayStatus == consts.PayStatusOk {
			err = service.SysUserOrder().PayNotify(ctx, &payin.NotifyCallFuncInp{Pay: &payLog})
			if err != nil {
				parser.Logger.Warningf(ctx, "cron PayOrderCheck Execute err:%+v", err)
				continue
			}
			return
		}
		var res *payin.QueryOrderModel
		res, err = payment.New(payLog.PayType).GetOrderInfo(ctx, payin.QueryOrderInp{OutTradeNo: payLog.OutTradeNo})
		if err != nil {
			parser.Logger.Warningf(ctx, "cron PayOrderCheck Execute err:%+v", err)
			continue
		}
		if res.Pay.PayStatus == consts.PayStatusOk {
			// 更新订单支付状态
			err = service.SysUserOrder().PayNotify(ctx, &payin.NotifyCallFuncInp{Pay: res.Pay})
			if err != nil {
				parser.Logger.Warningf(ctx, "cron PayOrderCheck Execute err:%+v", err)
				continue
			}
		}
	}
	return
}
